<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>促销活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加满减活动</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :model="ruleForm" :rules="rules" label-width="120px" ref="ruleForm" class="demo-ruleForm">
      <p>满减活动基本信息</p>
      <el-form-item label="分公司：" v-if="isBranch" class="is-required">
        <el-select v-model="ruleForm.branch" filterable clearable placeholder="请选择分公司">
          <el-option
            v-for="item in branchList"
            :label="item.branch_Name"
            :value="item.branch_Id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客资类型：" class="is-required">
        <el-select v-model="ruleForm.client" multiple>
          <el-option
            v-for="item in clientList"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动名称：" prop="name" class="is-required">
        <el-input v-model="ruleForm.name" style="width: 200px"></el-input>
        <el-checkbox style="margin-left: 20px" v-model="ruleForm.radio">设为副标题</el-checkbox>
      </el-form-item>
      <el-form-item label="标签：" prop="title">
        <el-input v-model="ruleForm.title" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="开始时间：" class="is-required">
        <el-date-picker type="datetime" value-format="yyyy-MM-dd-HH-mm-ss" placeholder="请选择时间" v-model="ruleForm.start" @change="start"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间：" class="is-required">
        <el-date-picker type="datetime" value-format="yyyy-MM-dd-HH-mm-ss" placeholder="请选择时间" v-model="ruleForm.end" @change="end"></el-date-picker>
      </el-form-item>
      <el-form-item label="满减类型：" class="is-required">
        <el-radio-group v-model="ruleForm.type">
          <el-radio label="1">每满元</el-radio>
          <el-radio label="2">阶梯</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === '1'" label="每满元：">
        满 <el-input v-model="ruleForm.full" style="width: 100px"></el-input> 元，
        减 <el-input v-model="ruleForm.reduce" style="width: 100px"></el-input> 元
      </el-form-item>
      <span v-show="ruleForm.type === '2'" class="stair">阶梯：</span>
      <el-form-item v-show="ruleForm.type === '2'"
        v-for="(item, index) in ruleForm.stair">
        满 <el-input style="width: 100px"  v-model="item.fullMoney "></el-input> 元，
        减 <el-input style="width: 100px"  v-model="item.reduceMoney"></el-input> 元
        <el-button v-show="index !== 0 " @click.prevent="remove(item)">删除</el-button>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === '2'" >
        <el-button @click="add_stair">新增阶梯</el-button>
      </el-form-item>
      <el-form-item label="参与频次：" class="is-required">
        <el-select v-model="ruleForm.frequency" style="width: 150px">
          <el-option label="不限制" value='1'></el-option>
          <!--<el-option label="每一用户" value='2'></el-option>-->
        </el-select>
        <span v-show="ruleForm.frequency === '2'">参与 <el-input @blur="numChange(ruleForm.num)" v-model="ruleForm.num" style="width: 100px"></el-input> 次</span>
      </el-form-item>
      <el-form-item label="活动说明：" prop="desc">
        <el-input type="textarea" v-model="ruleForm.explain" style="width: 500px"></el-input>
      </el-form-item>
      <p>商品信息</p>
      <el-button @click="simpleCheck">选择单品</el-button>
      <el-button @click="allDelete()">全部删除</el-button>
      <el-table
        :data="tableData"
        max-height="200"
        border
        style="width: 100%; margin-top: 10px">
        <el-table-column
          prop="productId"
          label="商品ID"
          align="center"
          width="">
        </el-table-column>
        <el-table-column
          prop="productName"
          label="商品名"
          align="center"
          width="">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="">
          <template scope="scope">
            <el-button v-show="scope.$index !== 0" @click="top(scope.$index, scope.row)" size="small">置顶</el-button>
            <el-button v-show="scope.$index !== 0" @click="moveT(scope.$index, scope.row)" size="small">上移</el-button>
            <el-button v-show="scope.$index !== (tableData.length - 1)" @click="moveB(scope.$index, scope.row)" size="small">下移</el-button>
            <el-button @click="omit(scope.$index, scope.row)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :total="total"
        style="padding-top:10px;text-align: right;">
      </el-pagination>
      <el-form-item style="margin-top: 30px; margin-left: -80px">
        <el-button type="primary" style="margin-right: 30px" @click="submit($event)">提  交</el-button>
        <el-button type="primary" style="margin-right: 30px" @click="submit($event)">保存草稿</el-button>
        <router-link :to="{'name': 'fullReduce' }">
          <el-button type="primary">取  消</el-button>
        </router-link>
      </el-form-item>
    </el-form>
    <!--选择单品弹窗-->
    <el-dialog class="dialog" title="选择商品" v-model="dialogSimple">
      <el-form style="margin-top: 20px; overflow: hidden" :inline="true" :model="formSimple" class="demo-form-inline">
        <el-form-item label="商品分类">
          <el-select v-model="formSimple.type1" style="width: 150px" filterable clearable @change="checkType2(formSimple.type1)">
            <el-option
              v-for="item in productList1"
              :label="item.cateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formSimple.type2" style="width: 150px" filterable clearable @change="checkType3(formSimple.type2)">
            <el-option
              v-for="item in productList2"
              :label="item.cateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formSimple.type3" style="width: 150px" filterable clearable>
            <el-option
              v-for="item in productList3"
              :label="item.cateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="formSimple.brand" style="width: 150px" filterable clearable>
            <el-option
              v-for="item in brandList"
              :label="item.brandName"
              :value="item.brandId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ID" placeholder="请输入商品ID">
          <el-input style="width: 100px" v-model="formSimple.ID"></el-input>
        </el-form-item>
        <el-form-item label="名称" placeholder="请查询的商品名称">
          <el-input style="width: 120px" v-model="formSimple.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="simpleList">搜索</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="lotAdd">批量添加</el-button>
        <el-button @click="allDelete2">全部删除</el-button>
      </div>
      <el-table
        :data="tableData2"
        v-loading.body="isLoading"
        height="200"
        ref="multipleTable"
        tooltip-effect="dark"
        border
        style="width: 100%"
        @select-all="handleSelectionChange"
        @selection-change="handleChange"
        @select="handleSingle">
        <el-table-column
          type="selection"
          :selectable="isCheck"
          width="55">
        </el-table-column>
        <el-table-column
          prop="productId"
          label="商品ID"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="productName"
          label="商品名称"
          align="center"
          width="300">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="">
          <template scope="scope">
            <el-button v-show="scope.row.name === 'add' && scope.row.remarks === undefined" @click="add(scope.$index, scope.row, $event)" size="small">添加</el-button>
            <el-button v-show="scope.row.name === 'cancel' && scope.row.remarks === undefined" @click="add(scope.$index, scope.row, $event)" size="small">撤销</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="remarks"
          label="备注"
          align="center"
          width="">
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total2"
        @current-change="handleCurrentChange2"
        :page-size="pageSize2"
        layout="total, prev, pager, next"
        :total="total2"
        style="padding-top:10px;text-align: right;">
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
//  import { apiURL } from '../../config/settings.js'
  import { mapState } from 'vuex'
  import { getInfo, cms } from '../../../config/proxy.js'
  import mixins from '../../../components/mixins.vue'
  export default {
    mixins: [mixins],
    data () {
      var checkName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('活动名称不能为空'))
        } else {
          callback()
        }
      }
      var checkTitle = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('标签不能为空'))
        } else if (value.length > 4) {
          return callback(new Error('不能超过四个字'))
        } else {
          callback()
        }
      }
      var checkNum = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('参与频次必须大于0'))
        } else {
          callback()
        }
      }
      return {
        rules: {
          title: [
            { validator: checkTitle, trigger: 'blur' }
          ],
          name: [
            { validator: checkName, trigger: 'blur' }
          ],
          num: [
            { validator: checkNum, trigger: 'blur' }
          ]
        },
        ruleForm: {
          branch: '',
          client: '',
          name: '',
          radio: false,
          title: '',
          start: '',
          end: '',
          type: '',
          stair: [
            {
              fullMoney: '',
              reduceMoney: ''
            }
          ],
          full: '',
          reduce: '',
          frequency: '',
          num: '',
          explain: ''
        },
        clientList: [],
        branchList: [],
//      商品信息
        tableData: [],
        total: '',
        currentPage: 1,
        pageSize: 10,
//      选择单品弹窗
        dialogSimple: false,
        brandList: [],
        productList1: [],
        productList2: [],
        productList3: [],
        formSimple: {
          type1: '',
          type2: '',
          type3: '',
          brand: '',
          ID: '',
          name: ''
        },
//      选择单品表格
        isLoading: false,
        tableData2: [],
        total2: '',
        currentPage2: 1,
        pageSize2: 10,
//      选中项的集合
        all: [],
//      路由参数
        data: ''
      }
    },
    methods: {
//    创建表单
      add_stair () {
        this.ruleForm.stair.push({
          fullMoney: '',
          reduceMoney: ''
        })
        console.log(this.ruleForm.stair)
      },
      freChange (val) {
//        console.log(val)
//        this.ruleForm.num = ''
//        this.ruleForm.frequency = val
      },
      numChange (val) {
        if (val <= 0) {
          this.$message({
            showClose: true,
            message: '参与频次不能小于0',
            type: 'error'
          })
          this.ruleForm.num = ''
        }
      },
      remove (item) {
        var index = this.ruleForm.stair.indexOf(item)
        if (index !== -1) {
          this.ruleForm.stair.splice(index, 1)
        }
      },
      submit (event) {
        if (this.ruleForm.type === '2') {
          for (var m = 0; m < this.ruleForm.stair.length - 1; m++) {
            if (Number(this.ruleForm.stair[m + 1].fullMoney) <= Number(this.ruleForm.stair[m].fullMoney) || Number(this.ruleForm.stair[m + 1].reduceMoney) < Number(this.ruleForm.stair[m].reduceMoney)) {
              this.$message({
                showClose: true,
                message: '每个阶梯必须大于上个阶梯',
                type: 'error'
              })
              return false
            }
          }
          for (var n = 0; n < this.ruleForm.stair.length; n++) {
            if (Number(this.ruleForm.stair[n].reduceMoney) > Number(this.ruleForm.stair[n].fullMoney)) {
              this.$message({
                showClose: true,
                message: '阶梯规格不合理！',
                type: 'error'
              })
              return false
            }
          }
        } else {
          if (Number(this.ruleForm.reduce) > Number(this.ruleForm.full)) {
            this.$message({
              showClose: true,
              message: '满减规格不合理！',
              type: 'error'
            })
            return false
          }
        }
        const start = new Date(this.ruleForm.start).getTime()
        const end = new Date(this.ruleForm.end).getTime()
        const now = new Date().getTime()
        this.branchList.forEach((item, index) => {
          if (item.branch_Name === this.ruleForm.branch) {
            this.ruleForm.branch = item.branch_Id
          }
        })
        console.log(this.ruleForm.client, '1')
        this.ruleForm.client.forEach((item1, index1) => {
          this.clientList.forEach((item2, index2) => {
            if (item1 === item2.name) {
              this.ruleForm.client[index1] = item2.id
            }
            return false
          })
        })
        console.log(this.ruleForm.client, '2')
        if (this.ruleForm.client.length === 0 || this.ruleForm.start === '' || this.ruleForm.end === '') {
          this.$message({
            showClose: true,
            message: '除活动说明外,均为必填项',
            type: 'error'
          })
          return false
        }
        if (this.tableData.length === 0) {
          this.$message({
            showClose: true,
            message: '商品信息至少为一条',
            type: 'error'
          })
          return false
        }
        if (start >= end) {
          this.$message({
            showClose: true,
            message: '请选择合理的时间范围',
            type: 'error'
          })
          return false
        }
        if (start <= now) {
          this.$message({
            showClose: true,
            message: '开始时间必须晚于当前时间',
            type: 'error'
          })
          return false
        }
        const Data = {
          branchId: this.branchId === 1 ? this.ruleForm.branch : this.branchId,
          editBy: this.userName,
          endTime: this.ruleForm.end,
          explain: this.ruleForm.explain,
          joinNum: this.ruleForm.frequency === '2' ? this.ruleForm.num : 0,
          label: this.ruleForm.title,
          name: this.ruleForm.name,
          products: this.tableData,
          rules: this.ruleForm.type === '1' ? [{fullMoney: this.ruleForm.full, reduceMoney: this.ruleForm.reduce}] : this.ruleForm.stair,
          startTime: this.ruleForm.start,
          subtitle: this.ruleForm.radio === true ? 1 : 2,
          type: this.ruleForm.type,
          userType: this.ruleForm.client.join(','),
          id: this.data.id
        }
        if (event.target.innerText === '提 交') {
          Data.state = 0
        } else {
          Data.state = -3
        }
        console.log(Data)
        cms.fullEdit(Data, (res) => {
          console.log(res)
          if (res.code === 0) {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'success'
            })
            this.$store.dispatch('delTab', {id: '1156'})
            this.$store.dispatch('manjianState', this.$store.state.updateState.manjianState + 1)
          } else if (res.code === 400) {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '请求服务器失败',
              type: 'error'
            })
          }
        })
      },
      start (val) {
        this.ruleForm.start = val
      },
      end (val) {
        this.ruleForm.end = val
      },
//    商品信息
      omit (index, row) {
        this.tableData.splice(index, 1)
      },
      allDelete () {
        this.tableData = []
      },
      top (index, row) {
        this.tableData.splice(0, 0, row)
        this.tableData.splice(index + 1, 1)
      },
      moveT (index, row) {
        this.tableData.splice(index - 1, 0, row)
        this.tableData.splice(index + 1, 1)
      },
      moveB (index, row) {
        this.tableData.splice(index + 2, 0, row)
        this.tableData.splice(index, 1)
      },
//    选择单品
      simpleCheck () {
        this.branchList.forEach((item, index) => {
          if (item.branch_Name === this.ruleForm.branch) {
            this.ruleForm.branch = item.branch_Id
          }
        })
        if (this.branchId === 1) {
          if (this.ruleForm.branch === '' || this.ruleForm.start === '' || this.ruleForm.client.length === 0 || this.ruleForm.end === '') {
            this.$message({
              showClose: true,
              message: '请选择分公司和活动开始时间',
              type: 'error'
            })
          } else {
            this.dialogSimple = true
            // 重置
            this.formSimple.ID = ''
            this.formSimple.name = ''
            this.formSimple.type1 = ''
            this.formSimple.type2 = ''
            this.formSimple.type3 = ''
            this.formSimple.brand = ''
            this.tableData2 = []
            this.currentPage2 = 1
            this.total2 = ''
          }
        } else if (this.ruleForm.start === '' || this.ruleForm.client.length === 0 || this.ruleForm.end === '') {
          this.$message({
            showClose: true,
            message: '请选择活动开始时间',
            type: 'error'
          })
        } else {
          this.dialogSimple = true
          // 重置
          this.formSimple.ID = ''
          this.formSimple.name = ''
          this.formSimple.type1 = ''
          this.formSimple.type2 = ''
          this.formSimple.type3 = ''
          this.formSimple.brand = ''
          this.tableData2 = []
          this.currentPage2 = 1
          this.total2 = ''
        }
      },
//    单品列表
      simpleList () {
        this.tableData2 = []
        this.currentPage2 = 1
        this.total2 = ''
        this.isLoading = true
        const queryData = {
          branchId: this.branchId === 1 ? this.ruleForm.branch : this.branchId,
          brandId: this.formSimple.brand,
          page: this.currentPage2,
          pageSize: this.pageSize2,
          productId: this.formSimple.ID,
          productName: this.formSimple.name,
          startTime: this.ruleForm.start,
          oneLevel: this.formSimple.type1,
          threeLevel: this.formSimple.type3,
          twoLevel: this.formSimple.type2
//          endTime: this.ruleForm.end,               // 新加的
//          priceType: this.ruleForm.client.join(',') // 新加的
        }
        cms.simple(queryData, (res) => {
          console.log(res)
          setTimeout(() => {
            this.isLoading = false
          }, 500)
          if (res.message === 'ok' && res.content !== null) {
            if (this.tableData.length !== 0) {
              for (var i = 0; i < res.content.content.length; i++) {
                let a = true
                for (var j = 0; j < this.tableData.length; j++) {
                  if (res.content.content[i].productId === this.tableData[j].productId) {
                    res.content.content[i].name = 'cancel'
                    a = false
                  } else {
                    res.content.content[i].name = 'add'
                  }
                  if (a === false) {
                    j = this.tableData.length
                  }
                }
              }
            } else {
              res.content.content.forEach(function (item, index) {
                item.name = 'add'
              })
            }
            this.tableData2 = res.content.content
            this.total2 = res.content.count
          } else if (res.message === 'ok' && res.content === null) {
            this.total2 = ''
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'error'
            })
            this.total2 = ''
          }
        })
      },
      checkType2 (val) {
        this.productList2 = []
        this.formSimple.type2 = ''
        this.formSimple.brand = ''
        cms.pType({pid: val}, (res) => {
          if (res.message === 'ok') {
            this.productList2 = res.content
          }
        })
      },
      checkType3 (val) {
        this.productList3 = []
        this.formSimple.type3 = ''
        cms.pType({pid: val}, (res) => {
          if (res.message === 'ok') {
            this.productList3 = res.content
          }
        })
        cms.brand({cateId: val}, (res) => {
          if (res.message === 'ok') {
            this.brandList = res.content
          }
        })
      },
      handleSingle (all, row) {

      },
      handleChange (all) {
        this.all = all
      },
      handleSelectionChange (all) {
        this.all = all
      },
      add (index, row, event) {
        if (event.target.innerText === '添加') {
          row.name = 'cancel'
          this.$refs.multipleTable.toggleRowSelection(row, true)
          if (this.tableData.indexOf(row) === -1) {
            this.tableData.unshift(row)
          }
        } else {
          row.name = 'add'
          this.$refs.multipleTable.toggleRowSelection(row, false)
          const index = this.tableData.indexOf(row)
          this.tableData.splice(index, 1)
        }
      },
      lotAdd () {
        this.tableData2.forEach((item1, index1) => {
          this.all.forEach(function (item, index) {
            if (item1.productId === item.productId) {
              item1.name = 'cancel'
            }
          })
        })
        this.all.forEach((item, index) => {
          if (this.tableData.indexOf(item) === -1) {
            this.tableData.unshift(item)
          }
        })
      },
      allDelete2 () {
        this.$refs.multipleTable.clearSelection()
      },
      handleCurrentChange2 (val) {
        this.currentPage2 = val
        this.tableData2 = []
        this.isLoading = true
        const queryData = {
          branchId: this.branchId === 1 ? this.ruleForm.branch : this.branchId,
          brandId: this.formSimple.brand,
          page: val,
          pageSize: this.pageSize2,
          productId: this.formSimple.ID,
          productName: this.formSimple.name,
          startTime: this.ruleForm.start,
          oneLevel: this.formSimple.type1,
          threeLevel: this.formSimple.type3,
          twoLevel: this.formSimple.type2
        }
        cms.simple(queryData, (res) => {
          console.log(res)
          setTimeout(() => {
            this.isLoading = false
          }, 500)
          if (res.message === 'ok' && res.content !== null) {
            if (this.tableData.length !== 0) {
              for (var i = 0; i < res.content.content.length; i++) {
                let a = true
                for (var j = 0; j < this.tableData.length; j++) {
                  if (res.content.content[i].productId === this.tableData[j].productId) {
                    res.content.content[i].name = 'cancel'
                    a = false
                  } else {
                    res.content.content[i].name = 'add'
                  }
                  if (a === false) {
                    j = this.tableData.length
                  }
                }
              }
            } else {
              res.content.content.forEach(function (item, index) {
                item.name = 'add'
              })
            }
            this.tableData2 = res.content.content
          }
        })
      },
      isCheck (row, index) {
        return !row.remarks && row.name === 'add'
      }
    },
    computed: mapState({
      userId: function (state) {
        if (!state.user.info.branchId) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.branchId
      },
      userName: function (state) {
        if (!state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.user_name
      },
      branchId: function (state) {
        if (!state.user.info.branchId) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.branchId
      }
    }),
    created () {
      this.data = this.$store.state.tab.uid
      console.log(this.data)
//    请求详情
      cms.fullDetail({id: this.data.id}, (res) => {
        console.log(res, '详情')
        if (res.message === 'ok') {
          this.ruleForm = {
            branch: res.content.branchName,
            client: res.content.userType,
            name: res.content.name,
            title: res.content.label,
            start: res.content.startTime,
            end: res.content.endTime,
            explain: res.content.explain,
            frequency: res.content.joinNum === 0 ? '1' : '2',
            type: res.content.type === '每满' ? '1' : '2',
            stair: [
              {
                fullMoney: '',
                reduceMoney: ''
              }
            ]
          }
          this.tableData = res.content.products
          if (res.content.joinNum !== 0) {
            this.ruleForm.num = res.content.joinNum
          }
          if (res.content.subtitle === 1) {
            this.ruleForm.radio = true
          }
          if (res.content.type === '每满') {
            this.ruleForm.full = res.content.rules[0].fullMoney
            this.ruleForm.reduce = res.content.rules[0].reduceMoney
          } else {
            this.ruleForm.stair = res.content.rules
          }
        } else {
          this.$message({
            showClose: true,
            message: '请求服务器失败',
            type: 'error'
          })
        }
      })
//    分公司
      cms.getBranch({}, (res) => {
        if (res.message === 'ok') {
          this.branchList = res.content
        }
      })
//    客资
      getInfo.client({}, (res) => {
        if (res.message === 'ok') {
          this.clientList = res.content.content
        }
      })
//    商品分类
      cms.pType({pid: 0}, (res) => {
        if (res.message === 'ok') {
          this.productList1 = res.content
        }
      })
    }
  }
</script>
<style>
  .dialog .el-form--inline div {
    display: inline-block;
    float: left;
  }
  .stair {
    margin-left: 66px;
    font-size: 14px;
    color: #48576a;
  }
</style>
